package
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.utils.IDataInput;
	
	import org.musince.global.$log;
	import org.musince.logic.ParamList;
	import org.musince.net.IDataOutputNet;
	import org.musince.net.IDataReceiver;
	import org.musince.net.IDataSender;
	import org.musince.net.OutputStream;
	import org.musince.net.Tunnel;
	
	public class ShortQuery implements IDataReceiver
	{
		public var tunnel:Tunnel;
		public var callback:Function;
		public var methodName:String;
		public var params:Array;
		public var stream:OutputStream;
		public var onError:Function;
		
		public function ShortQuery()
		{
			
		}
		
		public function prepare(methodName:String, argsNum:int):IDataOutputNet {
			this.methodName = methodName;
			tunnel = new Tunnel();
			tunnel.attachReceiver(this);
			stream = tunnel.getOutputStream();
			stream.writeInt(400);
			$protocol.writeHead(stream, "RPC", 0);
			stream.writeUTF(methodName);
			stream.writeByte(argsNum);
			return stream;
		}
		
		public function send(callback:Function):void {			
			tunnel.addEventListener(Event.CONNECT, onConnect);
			tunnel.addEventListener(Event.CLOSE, onClose);
			tunnel.addEventListener(IOErrorEvent.IO_ERROR, onClose);
			tunnel.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onClose);
			var host:String = "localhost";
			$log.debug("connecting to", host);
			tunnel.connect(host, 22222);
			this.callback = callback;			
		}
		
		public function onConnect(e:Event):void
		{		
			$log.debug("connect success, send query");
			stream.flush();
		}
		
		public function onClose(e:Event):void
		{
			if (null != onError) {
				onError(this);
			}
//			tunnel.close();
		}
		
		public function on_data(tunnel:Tunnel, stream:IDataInput):void {
			var version:int = stream.readInt();
			var msg:String = stream.readUTF();
			stream.readInt();
			if (msg == "QueryResult") {
				callback(stream);
			}
			tunnel.close();
		}
	}
}